﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel;

using EasyProp.Extensions;
using Castle.Core.Interceptor;

namespace EasyProp
{
    public class MarkObjectAsDirty : IPropertySetterFilter
    {
        #region IPropertySetterFilter Members

        public bool Execute(IInvocation invocation, string propertyName)
        {
            if (invocation.Arguments == null || invocation.Arguments.Count() == 0) return true;

            // Don't intercept self
            if (propertyName == ISDIRTY_PROPERTY_NAME) return true;

            PropertyInfo isDirtyPropertyInfo = invocation.TargetType.GetProperty(ISDIRTY_PROPERTY_NAME);
            if (isDirtyPropertyInfo != null && isDirtyPropertyInfo.CanWrite)
            {
                isDirtyPropertyInfo.SetValue(invocation.InvocationTarget, true, null);
            }

            return true;
        }

        #endregion

        const string ISDIRTY_PROPERTY_NAME = "IsDirty"; 
    }
}
